<?php

namespace app\home\services;

use app\common\loader\ModelMerchant;
use app\common\loader\ModelShop;
use app\common\loader\ModelVirtual;
use app\home\loader\Model;
use JsonException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

/**
 * 虚码活动
 */
class VirtualPromoService extends BaseService
{


    /**
     * 虚码活动列表
     * @param  $mer_id |商户id
     * @param  $product_code |商品code
     * @throws Exception
     */
    public function getProductActivity($mer_id, $product_code, $open_id, $lng, $lat, $user_id): array
    {
        //距离验证
        ModelShop::ShopSalesman()->validDistance($open_id, $mer_id, $lng, $lat);
        //获取商品活动规则
        $activity = ModelVirtual::VirtualPromo()->getVirtualPromoProduct($mer_id, $product_code, $user_id);

        // >1 为混合活动
        if (count($activity) > 1) {
            //混合
            $vp_id = 0;
            $type = 3;
            $small_ticket = 0;
        } else {
            $info = current($activity);
            $type = $info['product_type'];
            $small_ticket = $info['option']['small_ticket'];
            $vp_id = $info['id'];
        }

        //商品； 活动id； 类型：1 单商品,2联合商品,3混合商品； 小票：1需要 0 不需要；
        return [
            'product_code' => $product_code,
            'vp_id' => $vp_id,
            'type' => $type,
            'small_ticket' => $small_ticket,
        ];
    }


    /**
     * 虚码活动列表
     * @param  $mer_id |商户id
     * @param  $product_code |商品code
     * @throws Exception
     */
    public function getActivity($mer_id, $product_code, $user_id)
    {
        // 根据商品获取活动
        $activity = ModelVirtual::VirtualPromo()->getVirtualPromoProduct(
            $mer_id,
            $product_code,
            $user_id
        );

        //获取活动商品信息
        return Model::VirtualPromoProduct()->getActivityProductList(
            $mer_id,
            $activity,
            $user_id,
            $product_code
        );
    }


    /**
     * 虚码活动选择
     * @param  $mer_id |商户id
     * @param  $product_code |商品code
     * @param  $activity_id |活动id
     * @param  $user_id |导购id
     * @throws Exception
     */
    public function getActivityInfo($mer_id, $activity_id, $product_code, $user_id)
    {
        //特殊规则 导购是否可以参加活动
        $activity_info = Model::VirtualPromo()->getValidPromInfo((int)$activity_id, (int)$user_id);

        //联合获取该活动下的所有需要参与商品
        $activity_product_list = Model::VirtualPromoProduct()->getActivityProduct(
            $mer_id,
            $activity_id,
            $product_code,
            $activity_info['product_type']);
        $union = $activity_info['union'] ?? [];
        // 按数量处理
        $sum = 0;
        //
        if (!empty($union) && $union['rule'] === 2) {
            $sum = (int)$union['sum'];
        }
        return [
            'id' => $activity_info['id'],
            'product_type' => $activity_info['product_type'],
            'title' => $activity_info['title'],
            'small_ticket' => $activity_info['small_ticket'],
            'sum_product_num' => $sum,
            'union_rule' => $union['rule'],
            'product_list' => $activity_product_list,
        ];
    }




    public function getProductTitle($data = []){
        $title = '';
        foreach ($data as $key => $v){
            $title .= $v['product_title'];
        }
        return $title;
    }

    /**
     * 销售查询
     * @param  $mer_id |商户id
     * @param  $user_id | 导购openid
     * @throws Exception
     */
    public function getMarket($where = [], $page = 1, $page_size = 30)
    {
        return ModelVirtual::VirtualUsedLog()->getMarket(
            $where,
            $page, $page_size);
    }


    /**
     * 提交
     * @param string $mer_id |商户id
     * @param string $order_no |订单号
     * @param int $user_id |导购ID
     * @param array $ticket |小票
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws JsonException
     * @throws ModelNotFoundException
     */
    public function submitActivitys(string $mer_id, string  $order_no, int $user_id, array $ticket): array
    {
        $where[] = ['order_no' , '=' , $order_no];
        $where[] = ['num' , '>' , '0'];
        $where[] = ['mer_id' , '=' , $mer_id];
        $where[] = ['user_id' , '=' , $user_id];
        $product_list = ModelVirtual::VirtualScanTempLog()->list($where , 'product_code as code , num, vp_id');
        if (empty($product_list)) {
            throw  new Exception('扫码记录无效，请重新扫码后提交.', API_ERROR);
        }
        $vp_id = $product_list[0]['vp_id'];

        //导购是否可以参加活动
        $promModel = Model::VirtualPromo();
        $virtual_data = $promModel->getValidPromInfo($vp_id, $user_id);


        // 判断小票
        if ($virtual_data['small_ticket'] === 1 && empty($ticket)) {
            throw  new Exception('活动要求上传小票,请先上传小票后再提交.', API_ERROR);
        }
        // 判断总限制数
        if ($virtual_data['limit_num'] > 0 && $virtual_data['scanned_num'] > $virtual_data['limit_num']) {
            throw  new Exception('活动领取次数已用完,请联系销售商.', API_ERROR);
        }

        // 活动日限制数量
        if ($virtual_data['day_limit'] > 0) {
            $used_num = $promModel->userScanNumForToday($mer_id, $vp_id, $user_id);
            if ($used_num >= $virtual_data['day_limit']) {
                throw  new Exception('您今天扫码次数已达到上限,请每天继续扫码参加活动.', API_ERROR);
            }
        }


        // 验证商品是否满足活动要求并返回整理后商品数据
        $product_list = ModelVirtual::VirtualPromoProduct()->validVirtualPromoProduct(
            $mer_id,
            $vp_id,
            $product_list,
            $virtual_data['product_type'],
            $virtual_data['union']
        );


        // 验证门店库存 是否满足活动要求
        ModelShop::ShopStock()->validShopStoke($mer_id, $virtual_data['shop_id'], $product_list);


        // 保存活动数据
        $log_id =   $promModel->submitActivity($mer_id, $vp_id, $user_id, $virtual_data, $product_list, $ticket,$order_no);

        //导购信息
        $shop_salesman = $virtual_data['sales_man'];


        $remark = '红包正在派发中,即将到帐，请稍后！可提醒导购到微信零钱查询。';
        $memo = '(发放中)';
        if ($virtual_data['recheck_record'] === 1){
            $remark = '导购已完成销售，请尽快到后台查看，审核通过后红包到账。';
            $memo = '(待审核)';
        }
        // 触发提交成功的通知
        $data =  ModelVirtual::VirtualUsedLog()->getInfo(['id' => $log_id]);
        if (!empty($data)){
            if (empty($data['admin_info']['open_id'])){
                $data['admin_info']['open_id'] = ModelMerchant::Merchant()->where(['mer_id' => $mer_id,'is_manager' => 1])
                    ->value(null,'open_id');
            }
            event('OrderBalanceSubmit', [
                'title' => $data['product_title'],
                'type' => $data['vp_title'],
                'money' => $virtual_data['red_packet'].' 元 ' . $memo . '; 积分+'.$virtual_data['point'],
                'time' => date('Y-m-d H:i:s'),
                'shop_name' => $data['shop_title'] .':'. $data['salesman_name'],
                'balance' => $data['admin_info']['balance'] ?? 0,
                'remark' => $remark,
                'open_id' => $data['admin_info']['open_id'],
            ]);
        }
        if (empty($virtual_data['red_packet']) && empty($virtual_data['point'])){
            ModelMerchant::MerchantInfo()->throwErrorMerchant($mer_id , API_EXCEPTION , '本商品导购奖励已暂停',[
                0 => '感谢您成功销售商品',
                1 => '由于本商品的导购奖励已经暂停，所以本次销售无法领取红包和积分，如有疑惑，请与供货商联系!',
            ] , $data['salesman_name']);
        }

        //商户金额不足抛出异常
        if ($virtual_data['recheck_record']  >  ModelMerchant::MerchantStock()->where('mer_id' , $mer_id)->value(null,'balance')){
            ModelMerchant::MerchantInfo()->throwErrorMerchant($mer_id , API_EXCEPTION , '红包余额不足！',[
                0 => '感谢您成功销售商品',
                1 => '由于红包余额不足，本次销售奖励无法及时到账。供货商充值后，即可到账。',
                2 => '您也可以通知供货商尽快充值红包，谢谢配合！',
            ] , $data['salesman_name']);
        }


        return [
            'product' => $product_list,
            'point' => $virtual_data['point'] ?? 0,
            'name' => $shop_salesman['name'] ?? '导购',
            'all_point' => $shop_salesman['point'] ?? 0
        ];
    }

    //获取订单信息
    public  function  getOrderScan($order_no,$mer_id,$user_id){

        $where = [
            'order_no' => $order_no,
            'mer_id' => $mer_id,
            'user_id' => $user_id,
        ];
        $product_list = ModelVirtual::VirtualScanTempLog()->list($where , 'product_code as code , num');
        if (empty($product_list)) {
            throw  new Exception('扫码记录无效，请重新扫码后提交.', API_ERROR);
        }

        return $product_list;
    }
}
